<template>
  <a-row :wrap="false">
    <a-col flex="150px">
      <RouterLink to="/">
        <div class="title-bar">
          <img class="logo" src="../assets/logo.svg" alt="logo" />
          <div class="title">云图库</div>
        </div>
      </RouterLink>
    </a-col>
    <a-col flex="auto">
      <a-menu
        v-model:selectedKeys="current"
        mode="horizontal"
        :items="items"
        @click="doMenuClick"
      />
    </a-col>
    <a-col flex="none">
      <div class="user-login-status">
        <div v-if="loginUserStores.loginUser.id">
          <a-dropdown>
            <ASpace>
              <a-avatar :src="loginUserStores.loginUser.userAvatar"></a-avatar>
              {{ loginUserStores.loginUser.userName ?? '无名' }}
            </ASpace>
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <UserOutlined />
                  <RouterLink to="/user/outlined">个人信息</RouterLink>
                </a-menu-item>
                <a-menu-item @click="doLogout">
                  <LoginOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
        <div v-else>
          <a-button type="primary" href="/user/login">登录</a-button>
        </div>
      </div>
    </a-col>
  </a-row>
</template>
<script lang="ts" setup>
import { h, ref } from 'vue'
import { HomeOutlined, LoginOutlined,UserOutlined } from '@ant-design/icons-vue'
import { MenuProps, message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStores } from '@/stores/useLoginUserStores.ts'
import { userLogoutUsingPost } from '@/api/userController.ts'

const loginUserStores = useLoginUserStores()

const current = ref<string[]>([])
const router = useRouter()

const doMenuClick = ({ key }: { key: string }) => {
  router.push({
    path: key,
  })
}

const doLogout = async () => {
  const res = await userLogoutUsingPost()
  if (res.data.code === 0) {
    loginUserStores.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功！')
    router.push('/user/login')
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}

router.afterEach((to) => {
  current.value = [to.path]
})

const items = ref<MenuProps['items']>([
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '主页',
    title: '主页',
  },
  {
    key: '/admin/userManage',
    label: '用户管理',
    title: '用户管理',
  },
  {
    key: '/ant',
    label: h('a', { href: 'https://ant.design/', target: '_blank' }, 'ANT.DESIGN'),
    title: 'ant.design',
  },
])
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
